package com.xyy.ec.qualification.config;

import com.xyy.ec.qualification.utils.LoadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.Socket;
import java.util.Random;

@Slf4j
@Component
public class SerPortConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        int port = getAvailablePort();
        factory.setPort(port);
        LoadProperties properties = LoadProperties.get();
        properties.setProperty("port", String.valueOf(port));
        properties.writeProperties();
    }

    /**
     * 获取随机端口
     */
    public int getAvailablePort() {
        int minPort = 10000;
        int maxPort = 65535;
        Random random = new Random();
        int maxRetryCount = maxPort - minPort;
        while (maxRetryCount > 0) {
            int port = random.nextInt(maxPort - minPort + 1) + minPort;
            boolean isUsed = isPortUsing(port);
            if (!isUsed) {
                log.info("客户端启动端口是：{}", port);
                return port;
            }
            maxRetryCount--;
        }
        log.info("系统暂无端口可用，运行结束");
        System.exit(1);
        return 0;
    }

    /**
     * 查看端口是否被占用
     *
     * @param port
     * @return
     */
    private boolean isPortUsing(int port) {
        boolean flag = false;
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", port);
            flag = true;
            log.info("端口{}已被占用", port);
        } catch (IOException e) {
            log.info("端口{}可以使用", port);
        }finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    log.info("socket资源未释放，客户端工具启动失败了！！！");
                }
            }
        }
        return flag;
    }
}
